package com.huige.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huige.utils.JwtHelper;
import com.huige.utils.Result;
import com.huige.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author 朱志辉
 * @Create 2024/7/24 下午5:51
 * @Version 1.0
 * Description:  登录包含拦截器，检查请求头包含有效token
 *      有 有效 放行
 *      没有或无效 返回504
 */
@Component
public class LoginProtectedInterceptors implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token
        String token = request.getHeader("token");
        //检查是否有效
        boolean expiration = jwtHelper.isExpiration(token);
        //有效放行
        if (!expiration) {
            //放行，没有过期
            return true;
        }
        // 无效返回504
        Result<Object> build = Result.build(null, ResultCodeEnum.NOTLOGIN);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(build);
        response.getWriter().print(s);
        return false;
    }
}
